package com.spring.web.adminmanage.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.spring.web.adminmanage.entities.Menu;
import com.spring.web.adminmanage.entities.User;
import com.spring.web.adminmanage.service.MenuService;
import com.spring.web.adminmanage.service.UserLoginLogService;
import com.spring.web.adminmanage.service.WebUserService;
import com.spring.web.adminmanage.utils.CookieUtil;
import com.spring.web.adminmanage.utils.IPUtil;
import com.spring.web.adminmanage.utils.StringUtil;
import com.spring.web.adminmanage.utils.SwordBCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by hetao on 2017/9/18
 */
@Controller
@RequestMapping("/manage")
public class LoginController {
	private Producer captchaProducer = null;
	  
    @Autowired
    public void setCaptchaProducer(Producer captchaProducer){
        this.captchaProducer = captchaProducer;  
    }
	@Autowired
	private MenuService menuService;
	@Autowired
	WebUserService userService;
	@Autowired
	UserLoginLogService userLoginLogService;
	@RequestMapping("/tologin")
	public String login() {
		return "login";
	}
	
	/**
	 * 登录验证
	 */
	@RequestMapping("/login")
	public String verification(String username, String userpassword, String code, String rememberMe,
                               HttpServletRequest request, HttpServletResponse response, Model model) {
		User userdata = userService.getUserByUsername(new User(username));
		HttpSession session = request.getSession();
		session.setMaxInactiveInterval(10*60*60);
		String sessionCode = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
		model.addAttribute("username", username);
		if (StringUtil.isEmpty(code)||!code.toLowerCase().equals(sessionCode)){//忽略验证码大小写
			model.addAttribute("msg", "验证码错误");
			return "login";
		}
		if (userdata==null) {
			model.addAttribute("msg", "用户不存在");
			return "login";
		}
		if (!SwordBCrypt.checkpw(username+userpassword, userdata.getSysPwd())) {
			model.addAttribute("msg", "密码错误");
			return "login";
		}
		if (userdata.getState()!=1) {
			model.addAttribute("msg", "该用户被禁用");
			return "login";
		}
//		String remoteAddr = request.getRemoteAddr();
		String remoteAddr = IPUtil.getRemortIP(request);
		userLoginLogService.addLoginLog(userdata.getId(), remoteAddr);
		//添加cookie
		if("on".equals(rememberMe)){
			String sid = SwordBCrypt.hashpw(userdata.getUsername()+userdata.getSysPwd()+remoteAddr);
			CookieUtil.addCookie(response, "uid",userdata.getUsername());
			CookieUtil.addCookie(response, "sid",sid);
		}
		session.setAttribute("loginUser", userdata);
		//设置服务端需要长期保存的信息
		List<Menu> menuList = new ArrayList<Menu>();
		if(userdata.getRole()!=null) {
			menuList = menuService.getMenuByRoleId(userdata.getRole().getId().toString()); //通过userid来读取对应的菜单列表\
		}
		session.setAttribute("menuList", menuList);
		session.setAttribute("nowTime", new Date());
		session.setAttribute("roleData", userdata.getRole());
        try {
			response.sendRedirect(request.getContextPath()+"/index");
		} catch (IOException e){
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping(value="/validateCode")
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception{
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        String capText = captchaProducer.createText();
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }
	
	@RequestMapping("/loginOut")
	public String loginOut(HttpServletRequest request, HttpServletResponse response){
		Cookie[] cookies = request.getCookies();
		if (cookies!=null){
			Cookie uid = CookieUtil.getCookie(cookies, "uid");
			Cookie sid = CookieUtil.getCookie(cookies, "sid");
			if (uid!=null&&sid!=null) {
				uid.setMaxAge(0);
				sid.setMaxAge(0);
				uid.setPath("/");
				sid.setPath("/");
				response.addCookie(uid);
				response.addCookie(sid);
			}
		}
		request.getSession().setAttribute("loginUser", null);
		return "login";
	}

}